package com.ruoyi.framework.interceptor;

import com.ruoyi.common.annotation.AllowedIp;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

@Component
public class IpAccessInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            AllowedIp allowedIp = handlerMethod.getMethodAnnotation(AllowedIp.class);
            if (allowedIp != null) {
                String ipAddress = request.getRemoteAddr();
                if (!Arrays.asList(allowedIp.value()).contains(ipAddress)) {
                    throw new ServiceException(allowedIp.message());
                }
            }
        }
        return true;
    }
}
